#include "Symbol.h"
#include "Util.h"
using namespace std;

void Symbol::addSymbol(const string& name) {
    if(!this->visited(name)) { //not in the hash table
        this->Hash.insert(make_pair(name, new symNum(name, nullptr)));
    } else {
        return;
    }
}

void Symbol::removeSymbol(const string& name) {
    if(this->visited(name)) { //found in the hash table
        this->Hash.erase(name);
    } else {
        return;
    }
}

void* Symbol::getSymbolValue(const string& name) {
    //iterator to get the value
    symNum* num = this->Hash.find(name)->second;
    return num->value;
}

bool Symbol::visited(const string& name) {
    if(this->Hash.find(name) != this->Hash.end()) {
        return true; //found in the hash table
    }
    else {
        /*if not found, return false to addSymbol function 
        and add this symbol to the Hash*/
        return false;
    }
}

void Symbol::printTable() {
    FILE *fp = freopen(SymbolTxt, "w",stdout); //write
    cout << "name" << "\t" << "value" << endl;
    unordered_map<string, symNum*>::iterator it;
    for(it = this->Hash.begin(); it != this->Hash.end(); it++) {
        string name = it->first;
        void* value = it->second;
        cout << name << "\t" << value << endl;
    }
    fflush(fp);
    fclose(fp);
    freopen("CON","w",stdout);
}